package main

import (
	"chat/lib/chat"
	"chat/rpc"
	"chat/session"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"

	"golang.org/x/net/websocket"
)

var (
	flagHost string
	flagRpc  []string
)

func init() {
	flag.StringVar(&flagHost, "host", "127.0.0.1:8000", "listen host:port")
	flag.Var(newSliceValue([]string{"127.0.0.1:8001"}, &flagRpc), "rpc-hosts", "the server cluster list by , ")
}

func main() {
	flag.Parse()
	fmt.Println("run with flag: ", flagHost, flagRpc)

	http.Handle("/chat", websocket.Handler(agent))

	rpc.Init(flagRpc)
	chat.Mgr.SetCallBack(func(msg []*chat.Message) error {
		data, _ := json.Marshal(msg)
		session.BroadCast(data)
		return nil
	})

	fmt.Println("ListenAndServe on ", flagHost)
	err := http.ListenAndServe(flagHost, nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
